#!/bin/bash

# Description: 条件运算符 [] 和 [[  ]]
# File: conditional_operator.sh |Time: 2022-06-22 12:47

str="I am string"
if [[ $str = "I am string" ]]; then
    echo "[[]] true: I am string"
fi

# if [ $str = "I am string" ]; then
#     echo "[] true: I am string"
# fi
# 不能比较, 会报错: ./conditional_operator.sh: line 11: [: too many arguments
if [ "$str" = "I am string" ]; then
    echo "[] true: I am string"
 fi

#----------------------------------------------------------------------------
# [] 会把 > 号当作重定向符号, 所以无论怎么比都是true, 并且会创建名为36的文件
# if [ 35 > 36  ]; then
#     echo "[]: 35 > 36"
# else
#     echo "[]: 35 < 36"
# fi


if [[ 35 > 36 ]];then
    echo "[[]]: 35 > 36"
else
    echo "[[]]: 35 < 36"
fi

#----------------------------------------------------------------------------

# [] 会把&&当作shell命令执行, 下面的语句会报错: [: missing `]'
# if [ 0 && 1 ];then
#     echo "[]: true"
# else
#     echo "[]: false"
# fi

if [ "a" == "b" ];then
    echo "[]: true"
else
    echo "[]: false"
fi

# if [[ 300 > 200 && 200 > 100 ]]; then
if ! [[ 100 > 200 ]]; then
    echo "[[]]: true"
else
    echo "[[]]: false"
fi

#----------------------------------------------------------------------------
str="yes"

if [ $str = "y" -o $str = "yes"  ];then
    echo "[]: yes matched."
fi

if [[ $str =~ ^y(es)$  ]];then
    echo "[[]]: yes matched."
    echo "BASH_REMATCH[1]: ${BASH_REMATCH[1]}"
fi

if [[ $str = y* ]]; then
    echo "[[]]: y* = yes matched"
fi


# if [ -z "$str" ]; then           # 判断为空(字符串变量加引号)
# if [ -n "$str" ]; then           # 判断不为空(字符串变量加引号)
# if [ "$str" = "abc" ]; then      # 判断相等(字符串变量加引号)
# if [ "$str" == "abc" ]; then     # 判断相等(字符串变量加引号)
# if [ "$str" != "abc" ]; then     # 判断不相等(字符串变量加引号)
# if [ "$str1" \> "$str2" ]; then  # 判断大于(字符串变量加引号)
# if [ "$str1" \< "$str2" ]; then  # 判断小于


str=" "
str1=" "
if [[ -z $str ]];then
    echo "-z: str is empty"
else
    echo "-z: str is not empty"
fi

if [[ -n $str ]];then
    echo "-n: str is not empty"
else
    echo "-n: str is empty"
fi

if [[ $str == $str1 ]];then
    echo "str == str1"
else
    echo "str != str1"
fi




